package com.projectm.common;

import com.framework.common.utils.VerifyCodeUtils;
import com.projectm.common.to.Email;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * @author linyanbin
 * @date 2022/8/10 21:23
 */
@Service
public class EmailUtil {

    /** 用于被邮件内容中真正的验证码替换 **/
    private static final String VERIFY_CODES = "verifyCodes";
    /** 邮箱验证码长度 **/
    private static final int EMAIL_CODE_COUNTS = 6;
    /** 邮箱验证码邮箱时间 **/
    private static final long TIMEOUT = 3;
    /** 邮件标题 **/
    private static final String SUBJECT = "项目任务管理平台：重置用户密码";
    /** 邮件内容 **/
    private static final String TEXT = "您的验证码为:" + VERIFY_CODES + "，有效时间为" + TIMEOUT + "分钟，请尽快使用并且不要告诉别人。";
    @Autowired
    JavaMailSender javaMailSender;
    @Autowired
    RedisUtil redisUtil;

    /**
     * 因为Email是组件，所以需要自动注入才会取到properties中的值
     **/
    @Autowired
    Email email;

    /**
     * 发送验证码邮件给收件人
     * @param recipientEmail 收件人邮箱
     * @return String
     */
    public String sendEmail(String recipientEmail) {
        String verifyCodes = VerifyCodeUtils.generateVerifyCode(EMAIL_CODE_COUNTS, VerifyCodeUtils.DIGIT_VERIFY_CODES);
        String UUIDKey = UUID.randomUUID().toString();
        // 将验证码存到redis中，有效时间3分钟
        redisUtil.setVerificationKey(UUIDKey, verifyCodes, TIMEOUT);
        SimpleMailMessage message = new SimpleMailMessage();
        // 发件人邮箱
        message.setFrom(email.getUserName());
        // 收件人邮箱
        message.setTo(recipientEmail);
        // 邮箱标题
        message.setSubject(SUBJECT);
        // 设置文本内容
        message.setText(TEXT.replace(VERIFY_CODES, verifyCodes));
        javaMailSender.send(message);
        return UUIDKey;
    }
}
